$(function() {
	$("div#addForm input:reset").click(function(){
		$("div#addForm").fadeOut("slow"); 
	});
	
	$("table.datatable tr:even").addClass("evenRow");
	$("table.datatable tr:odd").addClass("oddRow");
	
	$(".editable").parent().click(function() {
		if($("#editing").is("input"))
			return;
		
		var pre = $.trim($(this).text());
		editEnable($(this).children('div'), pre);		
	});
	
	$("form#user").submit(function() {
		var ret = false;
		var params={};
		var parNames=['firstname','lastname','pesel'];		
		for(var i in parNames){
			var x = parNames[i];
			var abc = $("input#"+x).val();
			params[x]=$.trim(abc);
		}
		$.ajax({
			url: "/SpringMvcApp/app/customer/create/true",
			type: "POST",
			async: false,
			contentType: "application/json",
			dataType: 'json',
			data: JSON.stringify(params),
			success: function(msg){
				var errs = 0;
				for(var obj in msg){
					errs++;								
				}
				if(errs>0){
					alert('zonk forma');
				}else{
					$("div#addForm").fadeOut("slow");
					ret = true; 
				}
			},
			error: function(){
				alert('zonk');
			}
		});	
		return ret;	
	});
});

function editEnable(div, text, old){
	$(div).replaceWith('<input id="editing" type="text" value="'+text+'" />');

	$("#editing").focus().blur(function(){
		setTimeout('$("#editing").focus()',10);
	}).keypress(function(e){
		var code=e.keyCode;
		if(code==27){
			$(this).val(text);
			editDisable(this, text);
		}
		if (code==13){
			var post = $.trim($(this).val());
			if(old==null){
				old = text;
			}
			if(old == post){
				editDisable($('#async'), text);
				return;
			}
			var tr=$(this).closest('tr');
			
			$(this).replaceWith('<div id="async" class="editable">'+post+'</div>');
			var children = tr.children().not(':last');
			var params={};
			var parNames=['firstname','lastname','pesel'];		
			children.each(function(i){
				params[parNames[i]]=$.trim($(this).text());
			});					
			$.ajax({
				url: "/SpringMvcApp/app/customer/create/false",
				type: "POST",
				async: false,
				contentType: "application/json",
				dataType: 'json',
				data: JSON.stringify(params),
				success: function(msg){
					var errs = 0;
					for(var obj in msg){
						errs++;								
					}
					if(errs>0){
						editEnable($('#async'), post, old);
					}else{
						editDisable($('#async'), post);
					}
				},
				error: function(){
					editDisable($('#async'), text);
					alert('zonk');
				}
			});		
		}
	});
}

function editDisable(div, text){
	$(div).replaceWith('<div class="editable">'+text+'</div>');
}

function del(pesel){
	tr = $(this).closest("tr");	
	$.ajax({
		url: "/SpringMvcApp/app/customer",
		type: "DELETE",
		async: false,
		//dataType: 'json',
		data: JSON.stringify(pesel),
		success: function(){
			tr.remove();
		},
		error: function(){
			alert('zonk');
		}
	});	
}

function add(){
	$("div#addForm").fadeIn("slow");
}